package com.example.chess.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;

import androidx.annotation.Nullable;

import com.example.chess.utils.Utils;

public class CheckStateView extends View implements Checkable {

    private boolean isChecked;
    private Paint paint;
    private int borderWidth;
    private int offset;

    public CheckStateView(Context context) {
        this(context, null);
    }

    public CheckStateView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CheckStateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    private void initialize() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        borderWidth = Utils.dp2px(1.2f);
        offset = Utils.dp2px(3f);
    }

    @Override
    public void setChecked(boolean checked) {
        if (isChecked == checked) return;
        isChecked = checked;
        invalidate();
    }

    @Override
    public boolean isChecked() {
        return isChecked;
    }

    @Override
    public void toggle() {
        isChecked = !isChecked;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float halfBorderWidth = borderWidth / 2f;
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(borderWidth);
        canvas.drawRect(halfBorderWidth, halfBorderWidth,
                getWidth() - halfBorderWidth, getHeight() - halfBorderWidth, paint);

        if (isChecked()) {
            paint.setStyle(Paint.Style.FILL);
            canvas.drawRect(halfBorderWidth + offset, halfBorderWidth + offset,
                    getWidth() - halfBorderWidth - offset, getHeight() - halfBorderWidth - offset, paint);
        }
    }
}
